package com.google.code.p.restrpc.http;

import java.util.concurrent.locks.ReentrantLock;

import org.apache.http.client.HttpClient;

public class CachedHttpClientFactory implements HttpClientFactory {
    
    private HttpClientFactory factory;
    
    private ReentrantLock httpClientLock = new ReentrantLock();
    
    private HttpClient httpClient;
    
    private HttpClient singleHttpClient;
    
    public CachedHttpClientFactory(HttpClientFactory factory) {
        super();
        this.factory = factory;
    }
    
    public HttpClient getSingleThreadHttpClient() {
        if (singleHttpClient != null) {
            return singleHttpClient;
        }
        try {
            httpClientLock.lock();
            if (singleHttpClient != null) {
                return singleHttpClient;
            }
            singleHttpClient = factory.getSingleThreadHttpClient();
        }
        finally {
            httpClientLock.unlock();
        }
        return singleHttpClient;
    }
    
    public HttpClient getHttpClient() {
        if (httpClient != null) {
            return httpClient;
        }
        try {
            httpClientLock.lock();
            if (httpClient != null) {
                return httpClient;
            }
            httpClient = factory.getHttpClient();
        }
        finally {
            httpClientLock.unlock();
        }
        return httpClient;
    }
    
}
